import React, { Component } from 'react';
import { SearchPageContainer } from './searchPage.style'
import { SearchBar, Flex } from 'antd-mobile';
import Headerbar from '../../components/header/Headerbar'
import { HeadName } from 'components/details/detailStyle'
import { get } from 'utils/http'
import { connect } from 'react-redux'
import {withRouter} from 'react-router-dom'



@connect(
    state => {
        // console.log(state.getIn(['search','key']))
        return ({
            search: state.getIn(['search', 'key'])
        })
    },
    dispatch => ({
        changeKeywords(keywords) {
            dispatch({
                type: 'SAGA_SEARCH_RESULT',
                paylod: keywords
            })
        }
    })

)
@withRouter
class searchPage extends Component {
    constructor() {
        super()
        this.searchRef = React.createRef();
    }

    state = {
        value: [],
        num: 0,
        defaultValue: '',
        searchValue: '',
        resultList: [],
        heightListResult: [],
        isShow: false,
        hotList: [],
        searchResult: false
    };
    componentDidMount() {
        this.getHotList()
        this.props.changeKeywords('123')
        this.arr = localStorage.getItem('history')
        if (!this.arr) {
            this.arr = ['iphone', 'iphone11', 'ipad', 'iwatch', 'airpods', 'iphonese']
        } else {
            this.arr = this.arr.split(',')
        }
        this.setState({
            value: this.arr
        })
        // setTimeout(()=>{
        //     this.props.history.push('/result')
        // },1000)

        // console.log(this.props)
    }
    async getSearchResult(keywords) {
        // console.log(keywords)
        let data = await get({
            url: `http://h5test.wfdata.club/v1/search/advice?keyword=${keywords}&type=all`,
            params: {

            },
            headers: {
                'X-Request-Id': 'dgmxgkvRVZg+WaDX0YdMU6N6CO/H3U7PGly02rBHH2ZU6pldHMBk//l5L1Q+RDqF9MYuLFXxaPic0W60EC8gaA==',
                'X-Running-Env': 'Q3OVXEArMgZNlMHtAxpu7ONj6bFtJQXn/rvs04BOX697Tr585tFrKIfZg2KoeUpgvnQYU5SNJ6oll+TA3FcxhCSpa6SvJgmuq4xYqBNA20NJ8ldwleqG5XO+/pJxDWDxaNNMPz7ogAvZMCU05jjILfwfb4xVDID+l4bJCv3PvZscJDIQEUoUSJwLTyrr7tv+gqSf9UY9s9WYRpJ1JOgOJVE/R7GAEfmgKwxF17NRO5ggEi+HSU8VLk4VqV/x4hOj'
            }
        })
        // console.log(data)
        this.setState({
            resultList: data.data.dataList
        })
        if (this.state.resultList === undefined) {
            this.setState({
                resultList: []
            })
        }
        if (this.state.resultList) {
            this.light = this.state.resultList.reduce((value, item) => {
                let spArr = item.keyword.replace(keywords, `<span class="heighLight">${keywords}</span>`)
                value.push(spArr)
                return value
            }, [])
        }

        this.setState({
            heightListResult: this.light
        })

    }
    TagClick = item => {
        this.keywordSearch(item)
    }
    handleClick() {
        this.props.history.push('/index/information')
    }
    submit = val => {
        this.getSearchResult(val)

    }
    onChange(val) {
        this.setState({
            searchValue: val
        })
        this.getSearchResult(val)
        if (this.state.searchValue == '' || this.state.searchValue.length <= 1) {
            this.setState({
                isShow: false
            })
        } else {
            this.setState({
                isShow: true
            })
        }
    }

    async getHotList() {
        this.hot = await get({
            url: `http://h5test.wfdata.club/v1/search/hot`,
            headers: {
                'X-Request-Id': 'dgmxgkvRVZg+WaDX0YdMU6N6CO/H3U7PGly02rBHH2ZU6pldHMBk//l5L1Q+RDqF9MYuLFXxaPic0W60EC8gaA==',
                'X-Running-Env': 'Q3OVXEArMgZNlMHtAxpu7ONj6bFtJQXn/rvs04BOX697Tr585tFrKIfZg2KoeUpgvnQYU5SNJ6oll+TA3FcxhCSpa6SvJgmuq4xYqBNA20NJ8ldwleqG5XO+/pJxDWDxaNNMPz7ogAvZMCU05jjILfwfb4xVDID+l4bJCv3PvZscJDIQEUoUSJwLTyrr7tv+gqSf9UY9s9WYRpJ1JOgOJVE/R7GAEfmgKwxF17NRO5ggEi+HSU8VLk4VqV/x4hOj'
            }
        })
        this.setState({
            hotList: this.hot.data.dataList
        })
    }

    cancelHandler() {
        this.setState({
            searchValue: '',
            heightListResult: [],
            isShow: false,
        })
    }

    historyList() {
        this.state.value.unshift(this.keywords);
        if (this.state.value.length >= 15) {
            this.state.value.length = 15
        }
        localStorage.setItem('history', this.state.value)
        // console.log(this.state.value)
        this.setState({})
        // console.log(this.state.value)
        // console.log(this.keywords)
        localStorage.setItem('keywords', this.keywords)
        this.props.history.push(`/result/general?keywords=${this.props.keywords}`)
    }

    keywordSearch(key, id) {
        this.setState({
            // searchResult:true
        })
        if (id >= 0) {
            this.setState({
                searchValue: this.state.resultList[id].keyword
            })
            if (this.state.value.indexOf(this.state.resultList[id].keyword) > -1) {
                let index = this.state.value.indexOf(this.state.resultList[id].keyword)
                this.state.value.splice(index, 1)
            }
            this.keywords = this.state.resultList[id].keyword
            this.historyList()
        } else {
            this.setState({
                searchValue: key
            })
            if (this.state.value.indexOf(key) > -1) {
                let num = this.state.value.indexOf(key)
                this.state.value.splice(num, 1)
            }
            this.keywords = key
            this.historyList()
        }
    }

    backToHome=()=>{
        // this.props.history.push('/index')
        this.props.history.go(-1)
    }
    render() {
        return (
            <div style={{
                height: "100%"
            }}>
                <Headerbar>
                    <i className="yo-ico" style={
                        {
                            fontSize: "0.3rem",
                            marginLeft: '0.08rem'
                        }

                    }
                        onClick={this.backToHome}
                    >&#xe743;</i>
                    <HeadName>
                        <span className="titName">
                            搜索
                        </span>
                    </HeadName>

                </Headerbar>

                <SearchPageContainer>
                    <SearchBar ref={this.searchRef} type="text" placeholder="请输入搜索内容" value={this.state.searchValue}
                        onChange={val => this.onChange(val)}
                        onCancel={() => this.cancelHandler()}
                        onSubmit={val => this.submit(val)}
                    // onBlur={() => this.blurHandler()}
                    />
                    <ul>
                        {/* <i className="yo-ico">&#xe671;</i> */}
                        {
                            !this.state.searchResult && this.state.isShow == true && this.state.heightListResult && this.state.heightListResult.map((item, index) => {
                                return (
                                    <li className="keyWords" key={item} onClick={() => this.keywordSearch(item, index)}>
                                        <i className="yo-ico">&#xe671;</i>
                                        <p dangerouslySetInnerHTML={{ __html: item }}>
                                        </p>
                                    </li>
                                )
                            })
                        }
                    </ul>
                    {!this.state.searchResult && !this.state.isShow && <div>
                        <h1>热门搜索</h1>
                        <ul style={{
                            display: 'flex',
                            flexDirection: "row",
                            flexWrap: "wrap",
                            display: "-webkit-flex",
                            //    justifyContent:"space-between"
                        }}>
                            {
                                this.state.hotList.map((item, index) => {
                                    return (
                                        <li style={
                                            {
                                                background: "#f7f8fa",
                                                padding: "0.03rem 0.08rem",
                                                fontSize: "0.12rem",
                                            }
                                        } key={index} className="tag" data-seed="logId" onClick={() => this.TagClick(item.keyword)}>{item.keyword}</li>
                                    )
                                })
                            }
                        </ul>
                    </div>}


                    {!this.state.searchResult && !this.state.isShow && <div>
                        <h1>历史记录</h1>
                        <ul style={{
                            display: 'flex',
                            flexDirection: "row",
                            flexWrap: "wrap",
                            display: "-webkit-flex",
                        }}>
                            {
                                this.state.value.map((item, index) => {
                                    return (
                                        <li style={
                                            {
                                                background: "#f7f8fa",
                                                padding: "0.03rem 0.08rem",
                                                fontSize: "0.12rem",
                                            }
                                        } key={index} className="tag" data-seed="logId" onClick={() => this.TagClick(item)}>{item}</li>
                                    )
                                })
                            }
                        </ul>
                    </div>}

                </SearchPageContainer>
            </div>
        );
    }
}

export default searchPage;